//
//  DBYSDetailViewController.m
//  Estate
//
//  Created by wangdongdong on 16/8/9.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "FDAlertView.h"
#import "AlertVIew.h"
#import "ProcessRecordModel.h"
#import "SegmentViewController.h"
#import "BasicInformationViewController.h"
#import "JLLiuZhuanViewController.h"

#import "BaseDataViewController.h"
#import "AttachmentInformationVC.h"

#import "DBYSDetailViewController.h"


@interface DBYSDetailViewController ()
{
    FDAlertView *alert;
    //判断是否合格
    int _qualified;
}
@property (copy, nonatomic)NSString *content;
/**流程数据数组 */
@property (nonatomic,strong) NSMutableArray *processRecoedArray;
/**最新流程数据 */
@property (nonatomic,strong) ProcessRecordModel *currentRecordModel;
@end


@implementation DBYSDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    // 获取数据
    if (self.processId) {
        self.processRecoedArray = [self getProgessRecordModelArrayWithID:self.processId];

    }
    if(self.processRecoedArray.count==0) {
        [LSUtility showToastWithMessage:@"数据获取异常。" inView:self.view Andtime:1.8];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }

    //最新一条记录
    self.currentRecordModel = [self.processRecoedArray firstObject];
    
    // 流程类型
    if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE) { // 督办单
        self.title = @"督办单";
    } else if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW) { // 跟进单
        self.title = @"跟进单";
    }
    // 待审阅
    if (self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW) {
        [self createView];
        // 复查通过
    } else if (self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK_PASS_YES) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(shutDown)];
    }
    [self createsliderBtn];
}

#pragma MARK - 关闭流程
- (void)shutDown {
    WDDAlertController *alertVC = [WDDAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [LSUtility pushWDDAlertVC:alertVC withTitle:@"提示" andMessageStr:@"确认关闭流程吗? 关闭后改流程确认结束并归入历史列表."];
    // 确认
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self endProcess];
        [self addProcessRecordData];
        // 刷新督办列表
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDuBList" object:nil];
        // 通知首页刷新数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alertVC addAction:sure];
    
    // 取消
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:nil];
    [alertVC addAction:cancel];
    [self presentViewController:alertVC animated:YES completion:nil];
}



#pragma MARK - 菜单控制器添加
- (void)createsliderBtn {
    
    SegmentViewController *vc = [[SegmentViewController alloc]init];
    vc.height = DEF_SCREEN_HEIGHT - 108;
    NSMutableArray *controlArray = [[NSMutableArray alloc] init];
    
    // 基本信息
    BaseDataViewController *basicVC = [[BaseDataViewController alloc] init];
    basicVC.recordModel = [self.processRecoedArray firstObject];
    basicVC.addressInfo = self.addresInfo;
    basicVC.beginTime = self.beginTime;
    [controlArray addObject:basicVC];
    
    // 附件信息
    AttachmentInformationVC *attachmentVC = [[AttachmentInformationVC alloc] init];
    // 流程类型
    if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE) { // 督办单
        attachmentVC.duban = YES;
    } else if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW) { // 跟进单
        attachmentVC.genjin = YES;
    }
    attachmentVC.processRecoedArray = self.processRecoedArray;
    attachmentVC.currentRecordModel = self.currentRecordModel;
    [controlArray addObject:attachmentVC];
    
    // 流转信息
    JLLiuZhuanViewController *Detail_C=[[JLLiuZhuanViewController alloc]init];
    Detail_C.processRecordArray = self.processRecoedArray;
    [controlArray addObject:Detail_C];
    
    //设置选中字体颜色
    vc.titleSelectedColor = [TTTheme defaultManger].defaultColor;
    vc.buttonWidth = DEF_SCREEN_WIDTH/3;
    //添加标题
    vc.titleArray = @[@"基本资料", @"附件信息", @"流转信息"];
    //设置子视图
    vc.subViewControllers = controlArray;
    //标签栏背景色
    vc.headViewBackgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    //非选中状态下标签字体大小
    vc.fontSize=14.;
    //选中下划线颜色
    vc.bottomLineColor=[TTTheme defaultManger].defaultColor;
    vc.buttonHeight = 40.;
    
    [vc initSegment];
    [vc addParentController:self];
}

//获取流程记录
- (NSMutableArray *)getProgessRecordModelArrayWithID:(NSString *)ID{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME), date(CREATE_TIME) FROM PROCESS_RECORD WHERE PROCESS_ID = '%@' ORDER BY CREATE_TIME DESC", ID];
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *processRecordArray = [NSMutableArray array];
    
    while ([result next]) {
        ProcessRecordModel *prModel = [[ProcessRecordModel alloc] init];
        prModel.ID= [result stringForColumn:@"ID"];
        prModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        prModel.PROCESS_ID = [result stringForColumn:@"PROCESS_ID"];
        prModel.ADDRESS_ID = [result stringForColumn:@"ADDRESS_ID"];
        prModel.ADDRES_INFO = [result stringForColumn:@"ADDRES_INFO"];
        prModel.PROCESS_TYPE = [result intForColumn:@"PROCESS_TYPE"];
        prModel.PROCESS_STAGE = [result intForColumn:@"PROCESS_STAGE"];
        prModel.RECORD_USER = [result stringForColumn:@"RECORD_USER"];
        prModel.PROBLEM_TYPE = [result intForColumn:@"PROBLEM_TYPE"];
        prModel.RECORD_MASTER = [result stringForColumn:@"RECORD_MASTER"];
        prModel.RECIFY_USER = [result stringForColumn:@"RECIFY_USER"];
        prModel.RECIFY_UNIT = [result stringForColumn:@"RECIFY_UNIT"];
        prModel.SEVERITY = [result stringForColumn:@"SEVERITY"];
        prModel.END_TIME = [result stringForColumn:@"END_TIME"];
        prModel.SEND_TIME = [result stringForColumn:@"SEND_TIME"];
        prModel.SEND_TYPE = [result intForColumn:@"SEND_TYPE"];
        prModel.PROCESS_TITLE = [result stringForColumn:@"PROCESS_TITLE"];
        prModel.PROCESS_CONTENT = [result stringForColumn:@"PROCESS_CONTENT"];
        prModel.PROCESS_REQUIRED = [result stringForColumn:@"PROCESS_REQUIRED"];
        prModel.PROCESS_DESC = [result stringForColumn:@"PROCESS_DESC"];
        prModel.SUBMITTORS = [result stringForColumn:@"SUBMITTORS"];
        prModel.PUT_USER = [result stringForColumn:@"PUT_USER"];
        prModel.REVIEW_OPINION = [result stringForColumn:@"REVIEW_OPINION"];
        prModel.FILEINFOS = [result stringForColumn:@"FILEINFOS"];
        prModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        prModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        prModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        prModel.CREATE_DATE = [result stringForColumn:@"date(CREATE_TIME)"];
        prModel.SUBCREATE_TIME = [result stringForColumn:@"time(CREATE_TIME)"];
        prModel.zhuangtai = [result intForColumn:@"REVIEW_STATE"];
        prModel.REVIEW_USER = [result stringForColumn:@"REVIEW_USER"];
        //本地状态 用于判断能否编辑
        prModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        [processRecordArray addObject:prModel];
    }
    [db close];
    return processRecordArray;
}
#pragma MARK - 审阅
- (void)createView {
    if (self.isFirstparty) {
        return;
        
    } else {
        UIButton *btn_1=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
        btn_1.backgroundColor=[UIColor whiteColor];
        [btn_1 setTitle:@"通过" forState:UIControlStateNormal];
        btn_1.layer.cornerRadius=3.;
        btn_1.tag=100;
        btn_1.titleLabel.font=[UIFont systemFontOfSize:11.];
        [btn_1 setTitleColor:[UIColor colorWithRed:0.29 green:0.68 blue:0.64 alpha:1.00] forState:UIControlStateNormal];
        [btn_1 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *btn_2=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
        btn_2.tag=101;
        btn_2.backgroundColor=[UIColor whiteColor];
        btn_2.titleLabel.font=[UIFont systemFontOfSize:11.];
        btn_2.layer.cornerRadius=3.;
        [btn_2 setTitle:@"不通过" forState:UIControlStateNormal];
        [btn_2 setTitleColor:[UIColor colorWithRed:0.75 green:0.19 blue:0.23 alpha:1.00] forState:UIControlStateNormal];
        [btn_2 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *bar_Btn_1=[[UIBarButtonItem alloc]initWithCustomView:btn_1];
        UIBarButtonItem *bar_Btn_2=[[UIBarButtonItem alloc]initWithCustomView:btn_2];
        self.navigationItem.rightBarButtonItems=@[bar_Btn_2,bar_Btn_1];
    }
}

- (void)clickAction:(UIButton *)sender {
    if (sender.tag==100) {
        // 同意
        if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE && self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW) {  // 督办单
            _qualified = PROCESS_STAGE_END;
            
        } else if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW && self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW) {  // 跟进单
            _qualified = PROCESS_STAGE_DOING;
        }
        [self showAlert];
        
    }else if(sender.tag==101){
        // 不同意
        if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE && self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW) {  // 督办单
            _qualified = PROCESS_STAGE_CHECK;
            
        } else if (self.currentRecordModel.PROCESS_TYPE == PROCESS_TYPE_FOLLOW && self.currentRecordModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW) {  // 跟进单
            _qualified = PROCESS_STAGE_REVIEW_PASS_NO;
        }
        [self showAlert];
        
    }else if(sender.tag==102){
        //提交
        if (self.content && ![self.content isEqualToString:@""]) {
            [alert hide];
            [self reView];
        } else {
            [LSUtility showToastWithMessage:@"请输入说明" inView:self.navigationController.view Andtime:1.];
        }
    }else{
        //关闭审阅
        [alert hide];
    }
}

- (void)showAlert {
    
    alert = [[FDAlertView alloc] init];
    AlertVIew *contentView=[[AlertVIew alloc]initWithFrame:CGRECTS(0, 0, 300, 200)];
    
    contentView.textViewBlock=^(NSString *value){
        self.content = value;
    };
    
    //提交btn
    UIButton *submitBtn= contentView.submit;
    submitBtn.tag=102;
    [submitBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //关闭btn
    UIButton *closeBtn= contentView.closeBtn;
    closeBtn.tag=103;
    [closeBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //添加到alert
    alert.contentView = contentView;
    
    [alert show:self.view];
}

#pragma mark- 审阅(通知更新附件)
- (void)reView {
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    // 总监意见
    [dataDic setObject:self.content forKey:@"REVIEW_OPINION"];
    // 流程阶段
    [dataDic setObject:[NSString stringWithFormat:@"%d", _qualified] forKey:@"PROCESS_STAGE"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"directorReviewFollow" object:dataDic];
}

// 更新流程表
- (void)endProcess {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 流程表
    NSString *sqlStr = [NSString stringWithFormat:@"UPDATE PROCESS SET END_TIME = '%@', PROCESS_STAGE = '%d', LOCAL_MODIFY_STATE = 'MOD', MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'", [LSUtility nowTime],PROCESS_STAGE_END, DEF_PERSISTENT_GET_OBJECT(@"realname"), [LSUtility getIPAddress], [LSUtility nowTime], self.processId];
    
    if ([db executeUpdate:sqlStr]) {
        NSLog(@"关闭流程成功");
        
    } else {
        NSLog(@"关闭流程失败");
    }
}

// 添加流程记录
- (void)addProcessRecordData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":DEFISNUL([NSUUID UUID].UUIDString),
                 @"PRO_ID":DEFISNUL(self.currentRecordModel.PRO_ID),
                 @"PROCESS_ID":DEFISNUL(self.currentRecordModel.PROCESS_ID),
                 @"WEATHER":@"",
                 @"ADDRESS_ID":DEFISNUL(self.currentRecordModel.ADDRESS_ID),
                 @"ADDRES_INFO":DEFISNUL(self.currentRecordModel.ADDRES_INFO),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%d", self.currentRecordModel.PROCESS_TYPE],
                 @"PROCESS_STAGE":[NSString stringWithFormat:@"%d",PROCESS_STAGE_END],
                 @"RECORD_USER":DEFISNUL(self.currentRecordModel.RECORD_USER),
                 @"PROBLEM_TYPE":[NSString stringWithFormat:@"%d", self.currentRecordModel.PROBLEM_TYPE],
                 @"RECORD_MASTER":DEFISNUL(self.currentRecordModel.RECORD_MASTER),
                 @"RECIFY_USER":DEFISNUL(self.currentRecordModel.RECIFY_USER),
                 @"RECIFY_UNIT":DEFISNUL(self.currentRecordModel.RECIFY_UNIT),
                 @"SEVERITY":DEFISNUL(self.currentRecordModel.SEVERITY),
                 //三期bug解决 endtime为@""新增为空
                 @"END_TIME":@"",
                 //三期bug解决 endtime为@""新增为空
                 @"SEND_TIME":DEFISNUL(self.currentRecordModel.SEND_TIME),
                 @"SEND_TYPE":[NSString stringWithFormat:@"%d", self.currentRecordModel.SEND_TYPE],
                 @"PROCESS_TITLE":DEFISNUL(self.currentRecordModel.PROCESS_TITLE),
                 @"PROCESS_CONTENT":DEFISNUL(self.currentRecordModel.PROCESS_CONTENT),
                 @"PROCESS_REQUIRED":DEFISNUL(self.currentRecordModel.PROCESS_REQUIRED),
                 @"PROCESS_DESC":@"",
                 @"SUBMITTORS":DEFISNUL(self.currentRecordModel.SUBMITTORS),
                 @"PUT_USER":DEFISNUL(self.currentRecordModel.PUT_USER),
                 @"REVIEW_USER":DEFISNUL(self.currentRecordModel.REVIEW_USER),
                @"REVIEW_OPINION":DEFISNUL(self.currentRecordModel.REVIEW_OPINION),
                 @"REVIEW_STATE":[NSString stringWithFormat:@"%d", self.currentRecordModel.REVIEW_STATE],
                 @"FILEINFOS":DEFISNUL(self.currentRecordModel.FILEINFOS),
                 @"EXTEND_INFO":DEFISNUL(self.currentRecordModel.EXTEND_INFO),
                 @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":@"",
                 @"MODIFY_IP":@"",
                 @"MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_USER_NAME":@"",
                 @"LOCAL_MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS_RECORD];
    if(isAdd){
        NSLog(@"流程记录新增成功");
        
    }else{
        NSLog(@"流程记录新增失败");
    }
}

@end




